from flask import request, abort, jsonify
from . import todo_v1_bp
from ext import db
from app.models.todo import Todo
from flask_jwt_extended import jwt_required


@todo_v1_bp.route('/tasks', methods=['GET'])
# 需要验证token
@jwt_required()
def get_tasks_list():
    """
    查看所有任务
    """
    tasks_list = Todo.query.all()
    return jsonify({"count": len(tasks_list), 'tasks': [tasks.to_json() for tasks in tasks_list]}), 200


@todo_v1_bp.route('/tasks/<int:id>', methods=['GET'])
# 需要验证token
@jwt_required()
def get_task(id):
    """
    查看单条任务
    """
    task = Todo.query.get_or_404(id)
    return jsonify(task.to_json()), 200


@todo_v1_bp.route('/tasks', methods=['POST'])
# 需要验证token
@jwt_required()
def create_task():
    """
    创建单条任务
    """
    if not request.json or not 'title' in request.json or not 'description' in request.json:
        abort(400)
    new_todo = Todo()
    new_todo.title = request.json['title']
    new_todo.description = request.json['description']
    new_todo.done = False
    db.session.add(new_todo)
    db.session.commit()
    return jsonify({'task': new_todo.to_json()}), 201


@todo_v1_bp.route('/tasks/<int:id>', methods=['PUT'])
# 需要验证token
@jwt_required()
def update_task(id):
    """
    更新单条任务
    """
    if not request.json:
        abort(400)
    new_todo = Todo.query.get_or_404(id)
    if 'title' in request.json:
        new_todo.title = request.json['title']

    if 'description' in request.json:
        new_todo.description = request.json['description']

    if 'done' in request.json and type(request.json['done']) is not bool:
        new_todo.done = request.json['done']

    Todo.update(new_todo)
    return jsonify({'task': new_todo.to_json()}), 201


@todo_v1_bp.route('/tasks/<int:id>', methods=['DELETE'])
# 需要验证token
@jwt_required()
def delete_task(id):
    """
    删除单条任务
    """
    if not id:
        abort(400)
    post = Todo.query.get_or_404(id)
    Todo.delete(post, id)
    return jsonify({'msg': "删除成功"}), 200
